package mundo.java.client;

import mundo.java.client.events.FailureEvent;
import mundo.java.client.events.GreetingEvent;
import mundo.java.client.events.GreetingResponseEvent;
import mundo.java.client.events.MessageValidatedEvent;
import mundo.java.client.events.Event.Handler;
import mundo.java.shared.FieldVerifier;
import mundo.java.shared.GreetingAction;
import mundo.java.shared.GreetingResponse;

import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class ArtigoPresenter {
	@Inject
	public ArtigoPresenter(final GreetingServiceAsync service, final HandlerManager eventBus) {
		eventBus.addHandler(GreetingEvent.TYPE, new Handler<GreetingEvent>() {
			@Override
			public void onEvent(final GreetingEvent event) {
				// First, we validate the input.
				String textToServer = event.message;
				final GreetingAction action = new GreetingAction(textToServer);

				boolean messageValidated = FieldVerifier.isValidName(textToServer);
				eventBus.fireEvent(new MessageValidatedEvent(action, messageValidated));
				if (messageValidated) {
					// Then, we send the input to the server.
					service.greetServer(action, 
					new AsyncCallback<GreetingResponse>() {
						public void onFailure(Throwable caught) {
							eventBus.fireEvent(new FailureEvent(caught));
						}
	
						public void onSuccess(GreetingResponse response) {
							eventBus.fireEvent(new GreetingResponseEvent(action, response));
						}
					});
				}
			}
		});
	}
}